package com.ajie.service.impl;

import com.ajie.entity.Moment;
import com.ajie.entity.New;
import com.ajie.mapper.MomentMapper;

import com.ajie.service.CourseService;
import com.ajie.service.MomentService;
import com.ajie.service.NewService;
import com.ajie.utils.*;
import com.ajie.vo.MomentVo;
import com.ajie.vo.QuestVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Set;


@Service
@Slf4j
public class MomentServiceImpl implements MomentService {
    
    @Autowired
    private MomentMapper momentMapper;
    
    @Autowired
    private  MomentService momentService;
    
    @Autowired
    private  NewService newService;
    
    
    @Autowired
    private CourseService courseService;
    
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    JedisUtils jedisUtils ;
    
    
    @Override
    public Result findPage(QueryInfo queryInfo,String header) {
        log.info("该文件名是：MomentServiceImpl,该方法是：findPage");
        log.info("1.开始新闻咨询数据分页-->页码{}, -->页数{}, -->查询内容{}",queryInfo.getPageNumber(),queryInfo.getPageSize(),queryInfo.getQueryString());
        
        List<MomentVo> result = momentMapper.findPage(queryInfo.getQueryString());
        
        List<MomentVo> result1 = new ArrayList<>(result.size());
        log.info("从mysql查询结构遍历");
        result.forEach(momentVo ->{
            Long lookNum = jedisUtils.zscore("looks","moment::"+momentVo.getId()).longValue();
            Long likeNum = jedisUtils.zscore("likes","moment::"+momentVo.getId()).longValue();
            Long favouriteNum = jedisUtils.zscore("favourites","moment::"+momentVo.getId()).longValue();
            momentVo.setLookNum(lookNum);
            momentVo.setLikeNum(likeNum);
            momentVo.setFavouriteNum(favouriteNum);
            boolean b=false;
            boolean b1=false;
            boolean b2=false;
            if (header != null){
                Set<Object> set = redisUtil.sGet("momentId::"+ momentVo.getId().toString());
                //如果非空，遍、
                for (Object item2 : set){
                    String[] split = item2.toString().split("::");
                    String uid = split[2];
                    if (SecurityUtil.getUserId().toString().equals(uid)){
                        if ("look".equals(split[0])){
                            b = true;
                        }
                        if ("like".equals(split[0])){
                            b1 = true;
                        }
                        if ("favourite".equals(split[0])){
                            b2 = true;
                        }
                    }
                }
            }
            momentVo.setLook(b);
            momentVo.setLike(b1);
            momentVo.setFavourite(b2);
            
            if (momentVo.getTitle() == null){
                momentVo.setPicture(momentMapper.findPic(momentVo.getId())); ;
            }
            result1.add(momentVo);
        });
        result1.sort(Comparator.comparing(MomentVo::getCreateTime).reversed());
        //4.把list进行分页
        Page page = new Page(queryInfo.getPageNumber(),queryInfo.getPageSize());
        // 获取list的大小
        int total = result1.size();
    
        page.setTotal(total);
        int startIndex = (queryInfo.getPageNumber()-1) * queryInfo.getPageSize();
        int endIndex = Math.min(startIndex+queryInfo.getPageSize(),total);
        if (startIndex< total){
            page.addAll(result1.subList(startIndex,endIndex));
        }
    
        PageInfo<Object> objectPageInfo = new PageInfo<>(page);
        log.info("查询的总条数是-->{}",total);
        log.info("分页列表-->{}",objectPageInfo.getList());
        
        return new PageResult(total, objectPageInfo.getList());
    }
    
    @Override
    public Result insert(Moment moment) {
        momentMapper.insert(moment);
        redisUtil.zAdd("looks", "moment::" + moment.getId().toString(), 0);
        redisUtil.zAdd("likes","moment::" + moment.getId().toString(),0);
        redisUtil.zAdd("favourites","moment::" + moment.getId().toString(),0);
        return Result.success("插入动态数据成功！");
    }
    
    @Override
    public Result delete(Long id) {
        momentMapper.delete(id);
        return Result.success("删除动态成功");
    }
    
    @Override
    public Result update(Moment moment) {
        momentMapper.update(moment);
        return Result.success("更新动态成功");
    }
    
    @Override
    public Result insertQuest(QuestVo questVo) {
        Moment moment = new Moment();
        if (questVo.getTitle()!=null){
            moment.setTitle(questVo.getTitle());
        }
        moment.setContent(questVo.getContent());
        moment.setCreateTime(DateUtils.getDateTime());
        moment.setUserId(SecurityUtil.getUserId());
        momentMapper.insert(moment);
        String[] picture = questVo.getPicture();
        for (int i = 0; i < picture.length; i++) {
            momentMapper.insertImage(moment.getId(),picture[i]);
        }
        return Result.success("插入动态数据成功！");
    }
    
    @Override
    public List<MomentVo> getAll() {
        List<MomentVo> momentList = momentMapper.getAll();
        return momentList;
    }
    
    
    
    @Override
    public Result findPageByCreatedId(QueryInfo queryInfo,String header) {
        log.info("该文件名是：MomentServiceImpl,该方法是：findPageByCreatedId");
        log.info("1.开始新闻咨询数据分页-->页码{}, -->页数{}, -->查询内容{}",queryInfo.getPageNumber(),queryInfo.getPageSize(),queryInfo.getQueryString());
        List<MomentVo> result = momentMapper.findPage(queryInfo.getQueryString());
        List<MomentVo> result1 = new ArrayList<>(result.size());
        log.info("从mysql查询结构遍历");
        result.forEach(momentVo ->{
            Long lookNum = jedisUtils.zscore("looks","moment::"+momentVo.getId()).longValue();
            Long likeNum = jedisUtils.zscore("likes","moment::"+momentVo.getId()).longValue();
            Long favouriteNum = jedisUtils.zscore("favourites","moment::"+momentVo.getId()).longValue();
            momentVo.setLookNum(lookNum);
            momentVo.setLikeNum(likeNum);
            momentVo.setFavouriteNum(favouriteNum);
            boolean b = false;
            boolean b1 = false;
            boolean b2 = false;
            if (header != null){
                b = redisUtil.sHasKey("momentId::" + momentVo.getId().toString(), "look::userId::" + SecurityUtil.getUserId().toString());
                b1 = redisUtil.sHasKey("momentId::" + momentVo.getId().toString(), "like::userId::" + SecurityUtil.getUserId().toString());
                b2 = redisUtil.sHasKey("momentId::" + momentVo.getId().toString(), "favourite::userId::" + SecurityUtil.getUserId().toString());
            }
            momentVo.setLook(b);
            momentVo.setLike(b1);
            momentVo.setFavourite(b2);
        
            if (momentVo.getTitle() == null){
                momentVo.setPicture(momentMapper.findPic(momentVo.getId())); ;
            }
            result1.add(momentVo);
        });
        result1.sort(Comparator.comparing(MomentVo::getCreateTime).reversed());
        //4.把list进行分页
        Page page = new Page(queryInfo.getPageNumber(),queryInfo.getPageSize());
        // 获取list的大小
        int total = result1.size();
    
        page.setTotal(total);
        int startIndex = (queryInfo.getPageNumber()-1) * queryInfo.getPageSize();
        int endIndex = Math.min(startIndex+queryInfo.getPageSize(),total);
        if (startIndex< total){
            page.addAll(result1.subList(startIndex,endIndex));
        }
    
        PageInfo<Object> objectPageInfo = new PageInfo<>(page);
        log.info("查询的总条数是-->{}",total);
        log.info("分页列表-->{}",objectPageInfo.getList());
    
        return new PageResult(total, objectPageInfo.getList());
    }
    
    @Override
    public Result findPageCheck(QueryInfo queryInfo, String header) {
        log.info("该文件名是：MomentServiceImpl,该方法是：findPageCheck");
        log.info("1.开始新闻咨询数据分页-->页码{}, -->页数{}, -->查询内容{}",queryInfo.getPageNumber(),queryInfo.getPageSize(),queryInfo.getQueryString());
        PageHelper.startPage(queryInfo.getPageNumber(),queryInfo.getPageSize());
        Page<MomentVo> page = momentMapper.findPageCheck(queryInfo.getQueryString());
        long total = page.getTotal();
        List<MomentVo> result = page.getResult();
        List<MomentVo> result1 = new ArrayList<>(result.size());
        log.info("从mysql查询结构遍历");
        result.forEach(momentVo ->{
            if (momentVo.getTitle() == null){
                momentVo.setPicture(momentMapper.findPic(momentVo.getId())); ;
            }
            result1.add(momentVo);
        });
        log.info("查询的总条数是-->{}",total);
        log.info("分页列表-->{}",result1);
        return new PageResult(total, result1);
    }
    
    @Override
    public Result updateStatus(Long id) {
        momentMapper.updateStatus(id);
        return Result.success("审核完成");
    }
    
    
}
